
var cellinfo = {
  selected: 	null,
  highlighted: 	null
};



function Cell(i, x, y) {
  this.index = i;
  this.x = x;
  this.y = y;
  this.type = resource.grass;
  this.width = this.type.width;
  this.height = this.type.height;
  this.selected = false;
  this.highlight = false;
  this.objects = [];
};

Cell.prototype.setType = function(type) {
  this.type = type;
};

Cell.prototype.addObject = function(object) {
  if (object.cell != null)
    object.cell.removeObject(object);
  object.cell = this;
  object.cell_index = this.objects.length;
  this.objects[object.cell_index] = object;
};

Cell.prototype.removeObject = function(object) {
  this.objects.remove(object.cell_index);
  object.cell = null;
  object.cell_index = 0; 
};

Cell.prototype.contains = function(x, y) {
  var midx = (this.x - ooc.map.viewx) + this.width * 0.5;
  var midy = (this.y - ooc.map.viewy) + this.height * 0.5;      
  if (math.distance(midx, midy, x, y) < this.width * 0.5)
    return true;
  return false;
};

Cell.prototype.onmouseover = function() {
  if (this.highlight)
    return;
  if (cellinfo.highlighted != null)
  	cellinfo.highlighted.highlight = false;
  if (!this.selected) {
    this.highlight = true;
    cellinfo.highlighted = this;
  }
  ooc.redraw();
};

Cell.prototype.select = function() {
  if (cellinfo.selected != null)
  	cellinfo.selected.selected = false;
  this.highlight = false;
  this.selected = true;
  cellinfo.selected = this;

  // Moved the Overlord into this Cell is allowed
  var cell = ooc.currentOverlord().cell;
  if (math.distance(this.x, this.y, cell.x, cell.y) < this.width)
    ooc.currentOverlord().moveto(this);
    
  // Update the info box and actions
  ooc.info_terrain.innerHTML = this.getTerrain();
  
  ooc.info_actions.innerHTML = '';
  for (var i = 0; i < this.objects.length; i++)
    this.objects[i].showActions(ooc.info_actions);
};

Cell.prototype.getTerrain = function() {
  if (this.type == resource.grass) return 'Grass';
  if (this.type == resource.floor) return 'Floor';
};


Cell.prototype.draw = function(ctx) {
  ctx.drawImage(this.type, this.x , this.y);
  
  if (this.selected)
    ctx.drawImage(resource.selected, this.x , this.y);
    
  if (this.highlight) {
    var cell = ooc.currentOverlord().cell;
    var dist = math.distance(this.x, this.y, cell.x, cell.y);
    
    if (dist > this.width / 2 && dist < this.width)
      ctx.drawImage(resource.movable, this.x , this.y);
    else
      ctx.drawImage(resource.highlight, this.x , this.y);
  }
};